package com.modular.event;

import cn.hutool.core.lang.Opt;
import com.ToolOpt;
import com.modular.event.bean.AlarmEventDO;
import com.modular.event.bean.AlarmRecordsDO;
import com.modular.event.bo.AlarmInBO;
import com.tool.ToolRedisson;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.task.handle.fm.util.UtilFmMsg;

/**
 * @author: liuwenju
 * @date: 2023/6/5 13:26
 * @version: 1.0
 */
public class AlarmEventApi {

    /**
     * 告警事件保存
     * @param alarm 事件入参
     */
    public static final void alarmEvent(AlarmInBO alarm) {
        ToolRedisson.me.throttle_run("alarmEvent-" + alarm.getPointCode() + alarm.getAlarmEventCode(), () -> {
            // 获取告警事件
            AlarmEventDO alarmEventByCode = ToolOpt.OPT_ALARM_EVENT.getByCode(alarm.getAlarmEventCode());

            // 保存告警记录
            AlarmRecordsDO alarmRecordsDO = new AlarmRecordsDO();
            alarmRecordsDO.setTitle(Opt.ofBlankAble(alarm.getAlarmTitle()).orElseThrow(() -> new ComException("title 不能为空...")));
            alarmRecordsDO.setDesc(alarm.getAlarmDesc());
            alarmRecordsDO.setEventId(alarmEventByCode.getId());
            alarmRecordsDO.setHandlerId(alarm.getHandler());
            alarmRecordsDO.setStatus("1");
            alarmRecordsDO.setHandlerType(alarm.getHandlerType());
            alarmRecordsDO.setTenantId(alarmEventByCode.getTenantId());
            alarmRecordsDO.setSourceCode(alarm.getSourceCode());
            alarmRecordsDO.setIsRead("1");
            alarmRecordsDO.setExtDesc(alarm.getExtDesc());
            alarmRecordsDO.setPushStatus("1");
            alarmRecordsDO.setPointCode(alarm.getPointCode());
            alarmRecordsDO.setHandlerName(alarm.getHandlerName());
            alarmRecordsDO.setPointName(alarm.getPointName());
            alarmRecordsDO.setAlarmFile(alarm.getAlarmFile());

            // 消息推送
            Opt.ofBlankAble(alarm.getPushAlias()).ifPresent(s -> {
                String pushId = UtilFmMsg.msgPushApp(alarm.getPointCode(), alarmEventByCode.getName(), "其他", s);
                alarmRecordsDO.setPushId(pushId);
            });
            Opt.ofBlankAble(alarm.getPushPhone()).ifPresent(s -> {
                String pushId = UtilFmMsg.msgPushSms(alarm.getPointCode(), alarmEventByCode.getName(), "其他", s);
                alarmRecordsDO.setPushId(pushId);
            });
            // 推送状态
            alarmRecordsDO.setPushStatus("2");

            // 保存
            ToolOpt.OPT_ALARM_RECORDS.syncBean(alarmRecordsDO);
        }, 1000 * 60 * 10);
    }
}
